package com.niit.utils;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JOptionPane;

public class ConnectionUtil {
	
	private static final String DRIVER = "com.mysql.jdbc.Driver";
	private static final String URL = "jdbc:mysql://localhost:3306/library_system?useUnicode=true&characterEncoding=UTF-8";
	private static final String USERNAME = "root";
	private static final String PASSWORD = "root";
	
	
	public static Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName(DRIVER);
			conn = DriverManager.getConnection(URL, USERNAME,PASSWORD);
		} catch (Exception e) {
			
			JOptionPane.showMessageDialog(null, "数据库连接失败");
			e.printStackTrace();
		}
		
		return conn;
	}
	
	public static void close(Connection conn,PreparedStatement psmt, ResultSet rs) {
		closeConnection(conn);
		closeStatement(psmt);
		closeResultSet(rs);
	}
	
	
	private static void closeConnection(Connection conn){
		if(conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	private static void closeResultSet(ResultSet rs){
		if(rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	private static void closeStatement(Statement pstm){
		if(pstm != null) {
			try {
				pstm.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	
//	public static void main(String[] args) {
//		System.out.println(getConnection());
//	}
	
	
}
